﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using Hr.Model;
using Microsoft.EntityFrameworkCore.Internal;
using System.Web;
using Microsoft.EntityFrameworkCore.Query.Internal;
using System.ComponentModel;
using System.Data.Entity.Migrations;
using System.Security.Cryptography;

namespace Hr.DAL
{
    public class DashboardDAL
    {
        private DbContext db = DbContextFactory.Create();
        /// <summary>
        /// 控制面板获取所有相关数据
        /// </summary>
        /// <param name="pk_User"></param>
        /// <returns></returns>
        public Dictionary<string, object> GetDashboardInfo(int pk_User)
        {
            DateTime NowTime = DateTime.Now;
            //考勤只要：考勤类型、考勤时间最新的
            Attendance_List A = db.Set<Attendance_List>().OrderByDescending(n => n.CreateDate).FirstOrDefault(s => s.fk_User == pk_User);

            object Attendance = "";

            if (A != null)
            {
                int Y = DateTime.Parse(A.CreateDate.ToString()).Year;
                int M = DateTime.Parse(A.CreateDate.ToString()).Month;
                int D = DateTime.Parse(A.CreateDate.ToString()).Day;
                if (NowTime.Year == Y & NowTime.Month == M & NowTime.Day == D)
                {
                    Attendance = (from AT in db.Set<Attendance_List>()
                                  join Type in db.Set<Sys_TypeID>()
                                  on AT.TypeID equals Type.ID
                                  where Type.TableName.Equals("Attendance_List")
                                  && AT.fk_User == pk_User
                                  && AT.pk_Attendance == A.pk_Attendance
                                  select new
                                  {
                                      AT.CreateDate,
                                      Type.TypeName_CHS
                                  }).FirstOrDefault();
                }
            }




            if (Attendance == null)
            {
                Attendance = new { };
            }
            //便签
            IEnumerable<object> MemoList = db.Set<Memo_List>().Where(n => n.fk_User == pk_User).OrderByDescending(o => o.CreateDate).Select(s => new { s.pk_Memo, s.fk_User, s.CreateDate, s.Description }).Take(5);
            //简历：获取简历数量
            int ResumeCount = db.Set<Resume_List>().Count();
            //薪资：获取薪资数量
            int WageCount = db.Set<Wage_List>().Count();
            //人员管理
            int UserCount = db.Set<User_List>().Count();
            //任务量排行榜：循环userlist表,task_list里面的状态3是已完成
            List<object> UserTask = new List<object>();

            foreach (User_List item in db.Set<User_List>().Where(n => n.IsLock == false))
            {
                List<Task_List> TaskList = db.Set<Task_List>().Where(n => n.StatusID == 3 && n.fk_User == item.pk_User).ToList();
                Dictionary<string, object> ud = new Dictionary<string, object>()
                {
                    {"Name",item.FullName },
                    {"任务量",TaskList.Count() }
                };
                UserTask.Add(ud);
            }
            List<Notice_List> TopNiceList = (from NL in db.Set<Notice_List>()
                                             where NL.IsTop == true
                                             orderby NL.CreateDate
                                             descending
                                             select NL).ToList();

            TopNiceList.AddRange(db.Set<Notice_List>().Where(n => n.IsTop == false).OrderByDescending(n => n.CreateDate).ToList());
            //获取公告数据
            IEnumerable<object> NoticeList = (from NL in TopNiceList
                                              join UD in db.Set<User_Department>()
                                              on NL.fk_Department equals UD.pk_Department
                                              select new
                                              {
                                                  NL.pk_Notice,
                                                  UD.DepartmentName,
                                                  NL.CreateDate,
                                                  NL.Title,
                                                  NL.IsTop,
                                                  TypeName_CHS = db.Set<Sys_TypeID>().Where(n => n.TableName.Equals("Notice_List") & n.ID == NL.TypeID).FirstOrDefault().TypeName_CHS,
                                                  StatusName_CHS = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Notice_List") & n.ID == NL.StatusID).FirstOrDefault().StatusName_CHS,
                                                  Visual = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Notice_List") & n.ID == NL.StatusID).FirstOrDefault().Visual
                                              });

            //获取我的绩效任务
            IEnumerable<object> TaskListDesc = (from TL in db.Set<Task_List>()
                                                where TL.fk_User == pk_User
                                                orderby TL.CreateDate
                                                descending
                                                select new
                                                {
                                                    TL.pk_Task,
                                                    TL.CreateDate,
                                                    TL.Title,
                                                    TypeName_CHS = db.Set<Sys_TypeID>().Where(n => n.TableName.Equals("Task_List") & n.ID == TL.TypeID).FirstOrDefault().TypeName_CHS,
                                                    StatusName_CHS = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Task_List") & n.ID == TL.StatusID).FirstOrDefault().StatusName_CHS,
                                                    Visual = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Task_List") & n.ID == TL.StatusID).FirstOrDefault().Visual
                                                });

            //获取新闻数据
            IEnumerable<object> ArticleList = (from AL in db.Set<Article_List>()
                                               orderby AL.CreateDate
                                               descending
                                               select new
                                               {
                                                   AL.pk_Article,
                                                   AL.CreateDate,
                                                   AL.Title,
                                                   TypeName_CHS = db.Set<Sys_TypeID>().Where(n => n.TableName.Equals("Article_List") & n.ID == AL.TypeID).FirstOrDefault().TypeName_CHS,
                                                   StatusName_CHS = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Article_List") & n.ID == AL.StatusID).FirstOrDefault().StatusName_CHS,
                                                   Visual = db.Set<Sys_StatusID>().Where(n => n.TableName.Equals("Article_List") & n.ID == AL.StatusID).FirstOrDefault().Visual
                                               });


            //获取考勤信息
            List<object> AttList = new List<object>();
            foreach (Sys_TypeID item in db.Set<Sys_TypeID>().Where(n => n.TableName.Equals("Attendance_List")))
            {
                List<Attendance_List> AList = db.Set<Attendance_List>().Where(n => n.fk_User == pk_User & n.TypeID == item.ID).ToList();
                int Count = 0;
                foreach (Attendance_List a in AList)
                {
                    DateTime ATime = DateTime.Parse(a.CreateDate.ToString());
                    if (ATime.Year == DateTime.Now.Year & ATime.Month == DateTime.Now.Month)
                    {
                        Count++;
                    }
                }
                Dictionary<string, object> Ad = new Dictionary<string, object>()
                {
                    {"Type",item.TypeName_CHS},
                    {"次数",Count }
                };
                AttList.Add(Ad);

            }

            Dictionary<string, object> dt = new Dictionary<string, object>()
            {
                {"AttendanceInfo",Attendance },
                {"ResumeCount",ResumeCount },
                {"WageCount",WageCount },
                {"UserCount",UserCount },
                {"UserTask",UserTask },
                {"MemoList",MemoList },
                {"NoticeList",NoticeList },
                {"TaskListDesc",TaskListDesc },
                {"ArticleList",ArticleList },
                {"AttList",AttList }
            };
            return dt;
        }

        #region 便签操作

        /// <summary>
        /// 根据便签ID，获取单条便签信息
        /// </summary>
        /// <param name="pk_Memo"></param>
        /// <returns></returns>
        public Memo_List GetMemoInfo(int pk_Memo)
        {
            return db.Set<Memo_List>().SingleOrDefault(n => n.pk_Memo == pk_Memo);
        }

        /// <summary>
        /// 获取便签信息，模糊查询
        /// </summary>
        /// <param name="Term"></param>
        /// <returns></returns>
        public IEnumerable<Memo_List> GetMemoList(int pk_User, string Term)
        {
            if (Term == null)
            {
                Term = "";
            }
            return db.Set<Memo_List>().Where(n => n.Title.ToString().Contains(Term) & n.fk_User == pk_User).OrderByDescending(o => o.CreateDate);
        }

        /// <summary>
        /// 添加、修改便签
        /// </summary>
        /// <param name="M"></param>
        /// <param name="Type"></param>
        /// <param name="pk_User"></param>
        public void UpdateMemo(Memo_List M, string Type, int pk_User)
        {
            if (Type.Equals("Add"))
            {
                //添加
                M.fk_User = pk_User;
                M.fk_Department = db.Set<User_List>().SingleOrDefault(n => n.pk_User == pk_User).fk_Department;
                M.CreateDate = DateTime.Now;
                M.CreateUser = pk_User;
                db.Set<Memo_List>().Add(M);

            }
            else if (Type.Equals("Edit"))
            {
                //修改
                Memo_List ML = db.Set<Memo_List>().SingleOrDefault(n => n.pk_Memo == M.pk_Memo);
                ML.ModifyUser = pk_User;
                ML.ModifyDate = DateTime.Now;
                ML.Title = M.Title;
                ML.Description = M.Description;
                //db.Set<Memo_List>().AddOrUpdate(ML);
            }
        }


        /// <summary>
        /// 删除便签
        /// </summary>
        /// <param name="M"></param>
        public void DelMemo(Memo_List M)
        {
            db.Set<Memo_List>().Remove(M);
        }

        #endregion

        #region 个人设置操作

        /// <summary>
        /// 根据ID获取用户信息
        /// </summary>
        /// <param name="pk_User"></param>
        /// <returns></returns>
        public User_List GetUserListInfo(int pk_User)
        {
            return db.Set<User_List>().SingleOrDefault(n => n.pk_User == pk_User);
        }


        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="pk_User"></param>
        /// <param name="URL"></param>
        public void UpdateImg(int pk_User, string URL)
        {
            User_List UL = db.Set<User_List>().SingleOrDefault(n => n.pk_User == pk_User);
            UL.ImagePath1 = URL;
        }

        /// <summary>
        /// 用户中心修改用户信息
        /// </summary>
        /// <param name="U"></param>
        /// <param name="pk_User"></param>
        public void UpdateUserInfo(User_List U,int pk_User)
        {
            U.ModifyDate = DateTime.Now;
            U.ModifyUser = pk_User;
            db.Set<User_List>().AddOrUpdate(U);
        }
        #endregion
        public bool SaveChanges()
        {
            return db.SaveChanges() > 0;
        }
    }
}
